package session

import (
	"gitee.com/zhendliu/sorm/clause"
	"gitee.com/zhendliu/sorm/log"
	"gitee.com/zhendliu/sorm/parser"
	"time"
)

// Count records with where clause
func (s *Session) Count() (int64, error) {
	defer func(start time.Time) {
		s.Clear()
		elapsed := time.Since(start)
		log.InfoCaller("sql总时间 [%s]", parser.RoundDuration(elapsed))
	}(time.Now())

	tableNames, err := s.getTableNames()
	if err != nil {
		return 0, err
	}
	return s.countTable(tableNames)

}

func (s *Session) countTable(tableNames []string) (int64, error) {
	var cnt int64
	for _, tnameOwner := range tableNames {

		tname := parser.GetTableName(tnameOwner)
		db, ok := s.dbs[tname]
		if !ok { // 如果没有找到，就说明没有分表，就用默认的db
			db = s.db
		}
		s.clause.Set(clause.COUNT, tnameOwner)
		sql, vars := s.clause.Build(clause.COUNT, clause.WHERE)
		row := s.QueryRowContext(s.ctx, db.Db, db.Dia, sql, vars)
		var tmp int64
		if err := row.Scan(&tmp); err != nil {
			return 0, err
		}
		cnt += tmp
	}
	return cnt, nil
}
